package com.jspgou.cms.action.admin.assist;

import static com.jspgou.common.page.SimplePage.cpn;

import java.util.Dictionary;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.cms.entity.Consult;
import com.jspgou.cms.entity.Discuss;
import com.jspgou.cms.manager.ConsultMng;
import com.jspgou.cms.manager.DiscussMng;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.core.entity.ShopDictionary;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.LogMng;
import com.jspgou.core.manager.ShopDictionaryMng;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.core.web.WebErrors;



@Controller
public class ShopDictionaryAct {
	private static final Logger log = LoggerFactory.getLogger(ShopDictionaryAct.class);

	@RequestMapping("/dictionary/v_list.do")
	public String list(String queryType,Integer pageNo, HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(queryType,cpn(pageNo), CookieUtils
				.getPageSize(request));
		List<String>typeList=manager.getTypeList();
		model.addAttribute("pagination",pagination);
		model.addAttribute("pageNo",pagination.getPageNo());
		model.addAttribute("typeList",typeList);
		model.addAttribute("queryType",queryType);
		return "dictionary/list";
	}

	@RequestMapping("/dictionary/v_add.do")
	public String add(ModelMap model) {
		return "dictionary/add";
	}


	@RequestMapping("/dictionary/v_edit.do")
	public String edit(Integer id, Integer pageNo, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("shopDictionary", manager.findById(id));
		model.addAttribute("pageNo",pageNo);
		return "dictionary/edit";
	}
	

	@RequestMapping("/dictionary/v_ajax_edit.do")
	public void ajaxEdit(Integer id, HttpServletRequest request,HttpServletResponse response, ModelMap model) throws JSONException {
		JSONObject object = new JSONObject();
		ShopDictionary dic=manager.findById(id);
		if(dic!=null){
			object.put("id", dic.getId());
			object.put("name", dic.getName());
			object.put("type", dic.getType());
			object.put("value", dic.getValue());
		}
		ResponseUtils.renderJson(response, object.toString());
	}

	@RequestMapping("/dictionary/o_save.do")
	public String save(ShopDictionary bean, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.save(bean);
		log.info("save ShopDictionary id={}", bean.getId());
		logMng.operating(request, "添加字典项", "id="+bean.getId()+" ;name="+bean.getName());
		return "redirect:v_list.do";
	}

	@RequestMapping("/dictionary/o_update.do")
	public String update(ShopDictionary bean,String queryType, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateUpdate(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		//当更改某个字典项数据时，调用方法，相应更改咨询类型或评价类型
		updateType(bean);
		
		bean = manager.update(bean);
		log.info("update ShopDictionary id={}.", bean.getId());
		logMng.operating(request, "修改字典项", "id="+bean.getId()+" ;name="+bean.getName());
		return list(queryType,pageNo, request, model);
	}

	
	//抽取方法，更改商品咨询或者评价类型
	public void updateType(ShopDictionary bean){
		String Type=manager.findById(bean.getId()).getValue();
		//获取该字典的字典项分类
		String dictionaryType=manager.findById(bean.getId()).getType();
		//如果更改商品咨询类型
		if(dictionaryType.equals("consultType")){
			List<Consult> consults=consultMng.findByType(null,Type);
			if(consults!=null){
				for(Consult consult:consults){
					if(bean.getType().equals("consultType")){
						consult.setConsultType(bean.getValue());//修改consult表中对应consultType值。
						consultMng.update(consult);
					}else{
						//如果更改后，dictionaryType不等于consultType,相当于在字典相中删除该分类，需要删除数据库中相应的数据
						consultMng.deleteById(consult.getId());
					}
				}
			}
		}
		//如果更改的是商品评价类型
		if(dictionaryType.equals("discussType")){
			List<Discuss> discusses=discussMng.findByType(null,Type);
			if(discusses!=null){
				for(Discuss discuss :discusses){
					if(bean.getType().equals("discussType")){
						discuss.setDiscussType(bean.getValue());
						discussMng.save(discuss);
					}else{
						discussMng.deleteById(discuss.getId());
					}
				}
			}
		}
	}
	
	
	@RequestMapping("/dictionary/o_delete.do")
	public String delete(Integer[] ids, String queryType,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ShopDictionary[] beans = manager.deleteByIds(ids);
		for (ShopDictionary bean : beans) {
			//调用方法
			deleteDate(bean);
			log.info("delete ShopDictionary id={}", bean.getId());
			logMng.operating(request, "删除字典项", "id="+bean.getId()+" ;name="+bean.getName());
		}
		return list(queryType,pageNo, request, model);
	}
	
	//当删除数据字典时，相应的删除咨询或评价表中的数据
	public void deleteDate(ShopDictionary bean){
		String type=bean.getType();
		if(type.equals("consultType")){
			consultMng.deleteByType(bean.getValue());
		}
		if(type.equals("discussType")){
			discussMng.deleteByType(bean.getValue());
		}
	}
	
	
	@RequestMapping(value = "/dictionary/v_check_value.do")
	public void checkDateValue(String value, String type,HttpServletResponse response) throws JSONException {
		JSONObject json=new JSONObject();
		String pass;
		if (StringUtils.isBlank(value)) {
			pass = "false";
		} else {
			pass = manager.dicDeplicateValue(value, type) ? "true" : "false";
		}
		json.put("pass", pass);
		ResponseUtils.renderJson(response, json.toString());
	}

	private WebErrors validateSave(ShopDictionary bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if(manager.dicDeplicateValue(bean.getValue(), bean.getType())){
			errors.addErrorCode("shopDictionary.value.deplicate",bean.getType(), bean.getValue());
		}
		return errors;
	}
	
	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(ShopDictionary bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		ShopDictionary entity=manager.findById(bean.getId());
		if (vldExist(bean.getId(), web.getId(), errors)) {
			return errors;
		}
		if(!entity.getValue().equals(bean.getValue())&&!entity.getType().equals(bean.getType())){
			if(manager.dicDeplicateValue(bean.getValue(), bean.getType())){
				errors.addErrorCode("shopDictionary.value.deplicate",bean.getType(), bean.getValue());
			}
		}
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (errors.ifEmpty(ids, "ids")) {
			return errors;
		}
		for (Integer id : ids) {
			vldExist(id, web.getId(), errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, Long webId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		ShopDictionary entity = manager.findById(id);
		if(errors.ifNotExist(entity, ShopDictionary.class, id)) {
			return true;
		}
		return false;
	}
	
	@Autowired
	private ShopDictionaryMng manager;
	
	@Autowired
	private ConsultMng consultMng;
    @Autowired
    private DiscussMng discussMng;
    @Autowired
    private LogMng logMng;
	
}